#!/usr/bin/perl -w

#==================================================
# center
# File ID: 54673c7e-5d37-11df-bc5d-90e6ba3022ac
# Centers text
#==================================================

use strict;
use Getopt::Std;

our ($opt_w, $opt_h) =
    (    "",      0);
getopts('hw:');

if ($opt_h) {
	print(<<END);

Syntax: $0 [-w width] [file [files ...]]

Centers text from stdin or files. If no width is specified, the longest
line will be used.

END
	exit 0;
}

my @Lines = <>;
my $Longest = 0;

if ($opt_w) {
	if ($opt_w <= 0) {
		die("$opt_w: Invalid line length");
	} else {
		$Longest = $opt_w;
	}
} else {
	for (@Lines) {
		chomp;
		s/^\s*(.*?)\s*$/$1/;
		$Longest = length($_) if (length($_) > $Longest);
	}
}

for my $Curr (@Lines) {
	chomp($Curr);
	$Curr =~ s/^\s*(.*?)\s*$/$1/;
	my $curr_len = length($Curr);
	if ($curr_len < $Longest) {
		$Curr = (" " x int(($Longest-$curr_len)/2)) . $Curr;
		$Curr .= " " x ($Longest-length($Curr));
	}
	print("$Curr\n");
}
